package com.centaline.androidsalesblog.activities.mine;

import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.api.usercenter.UpdatePasswordApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.UserRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.interfaces.IResponseListener;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func3;
import rx.schedulers.Schedulers;

/**
 * 修改密码
 * <p/>
 * Created by fusl1 on 2015/12/28.
 * Modify by Lihq on 2016/01/17
 */
public class SettingsPassWordActivity extends BaseActivity {

    private RelativeLayout rl_old_password;//原密码
    private TextInputLayout til_settings_password_old;//原密码
    private TextInputLayout til_settings_password_new;//新密码
    private TextInputLayout til_settings_password_again_new;//再次输入新密码
    private Button bt_settings_password;//修改密码
    private EditText newPasswordEditText;

    private UserDo currentUserDo;
    private boolean hasPassWord;//有无密码

    @Override
    protected int setLayoutId() {
        return R.layout.activity_settings_password;
    }

    @Override
    protected void findViews() {
        rl_old_password = (RelativeLayout) findViewById(R.id.rl_old_password);
        til_settings_password_old = (TextInputLayout) findViewById(R.id.til_settings_password_old);
        til_settings_password_new = (TextInputLayout) findViewById(R.id.til_settings_password_new);
        til_settings_password_again_new = (TextInputLayout) findViewById(R.id.til_settings_password_again_new);
        bt_settings_password = (Button) findViewById(R.id.bt_settings_password);
    }

    @Override
    protected void initViews() {
        setUniversalToolbar(R.string.title_settings_password);

        EditText oldPasswordEditText = til_settings_password_old.getEditText();
        newPasswordEditText = til_settings_password_new.getEditText();
        EditText againPasswordEditText = til_settings_password_again_new.getEditText();

        if (oldPasswordEditText != null &&
                newPasswordEditText != null &&
                againPasswordEditText != null) {
            Observable<CharSequence> oldPasswordChangeObservable = RxTextView.textChanges(oldPasswordEditText);
            Observable<CharSequence> newPasswordChangeObservable = RxTextView.textChanges(newPasswordEditText).skip(1);
            Observable<CharSequence> againNewPasswordChangeObservable = RxTextView.textChanges(againPasswordEditText).skip(1);

            oldPasswordChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
                            final boolean oldPasswordValid = charSequence.length() > 5;
                            if (oldPasswordValid) {
                                if (charSequence.toString().equals(currentUserDo.getPassWord())) {
                                    til_settings_password_old.setError(null);
                                } else {
                                    til_settings_password_old.setError(getString(R.string.error_old_password));
                                }
                            } else {
                                til_settings_password_old.setError(getString(R.string.error_password));
                            }
                        }
                    });

            newPasswordChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
                            final boolean newPasswordValid = charSequence.length() > 5;
                            if (newPasswordValid) {
                                til_settings_password_new.setError(null);
                            } else if (til_settings_password_new.getError() == null) {
                                til_settings_password_new.setError(getString(R.string.error_password));
                            }
                        }
                    });

            againNewPasswordChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
                            final boolean againNewPasswordValid = charSequence.length() > 5;
                            if (againNewPasswordValid) {
                                if (newPasswordEditText.getText().toString().equals(charSequence.toString())) {
                                    til_settings_password_again_new.setError(null);
                                } else {
                                    til_settings_password_again_new.setError(getString(R.string.error_new_password));
                                }
                            } else {
                                til_settings_password_again_new.setError(getString(R.string.error_password));
                            }
                        }
                    });

            Observable.combineLatest(oldPasswordChangeObservable, newPasswordChangeObservable, againNewPasswordChangeObservable,
                    new Func3<CharSequence, CharSequence, CharSequence, Boolean>() {
                        @Override
                        public Boolean call(CharSequence oldPassword, CharSequence
                                newPassword, CharSequence againNewPassword) {
                            final boolean oldPasswordValid = !hasPassWord || (oldPassword.length() > 5 &&
                                    oldPassword.toString().equals(currentUserDo.getPassWord()));
                            final boolean newPasswordValid = newPassword.length() > 5;
                            final boolean againNewPasswordValid = againNewPassword.length() > 5 &&
                                    againNewPassword.toString().equals(newPassword.toString());
                            return oldPasswordValid && newPasswordValid && againNewPasswordValid;
                        }
                    })
                    .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            bt_settings_password.setEnabled(aBoolean);
                        }
                    });
        }


        RxView.clicks(bt_settings_password)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        requestUpdatePassword();
                    }
                });

        userInfo();
    }

    private void requestUpdatePassword() {
        hideKeyboard(til_settings_password_again_new);
        showLoadingDialog();
        UpdatePasswordApi updatePasswordApi = new UpdatePasswordApi(SettingsPassWordActivity.class, UserRo.class,
                new IResponseListener<UserRo>() {

                    @Override
                    public void onResponse(UserRo userRo) {
                        UserDo userDo = userRo.getUserDo();
                        if (userRo.getResultNo() == 0 &&
                                userDo != null) {
                            userSave(userDo);
                        } else {
                            cancelLoadingDialog();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        netWorkUnable();
                    }
                });
        updatePasswordApi.setPassword(newPasswordEditText.getText().toString());
        updatePasswordApi.startRequest();
    }

    /**
     * 用户信息
     */
    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo != null) {
                            currentUserDo = userDo;
                            if (TextUtils.isEmpty(currentUserDo.getPassWord())) {
                                hasPassWord = false;
                            } else {
                                hasPassWord = currentUserDo.getPassWord().length() < 21;
                            }
                            rl_old_password.setVisibility(hasPassWord ? View.VISIBLE : View.GONE);
                        }else{
                            rl_old_password.setVisibility(View.GONE);
                        }
                    }
                });
    }

    /**
     * 保存用户信息
     */
    private void userSave(UserDo userDo) {
        AppConstant.setUserLogin(this, userDo);
        RxDataBase.saveUser(userDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        cancelLoadingDialog();
                        toast("修改成功");
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }
}
